package com.webull.information.center.carwler.task;

import java.util.List;
import java.util.function.Consumer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.NewsTaskUtil;
import com.webull.information.center.carwler.task.handler.StockGoogleNewsHandler;
import com.webull.securities.client.model.Stock2Information;
import com.webull.securities.client.service.StockService;

@Component
public class News_GoogleFullStock_Task {

    protected final Logger logger = LogManager.getLogger(getClass());

    private @Autowired
    StockService stockService;

    private @Autowired
    StockGoogleNewsHandler stockGoogleNewsHandler;

    private @Autowired
    @Qualifier("executor_news")   ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private final Integer pageSize = 100;


    /**
     * 全量扫描
     *
     * @since 0.1.0
     */
    public Integer fullStockFinanceNewsExchangeCode(String exchangeCode) {
        return fullStockFinanceNewsExchangeCode(exchangeCode, -1, null);
    }

    public Integer fullStockFinanceNewsExchangeCode(String exchangeCode, Integer lastId, Integer loop) {
        logger.info("FullStockFinanceNews.fullStockFinanceNewsExchangeCode start exchangeCode:{},lastId:{},loop:{}", exchangeCode, lastId, loop);
        int loop_ = 0;
        full:
        do {
            if (loop != null && loop > 0 && ++loop_ > loop) {
                break full;
            }
            List<Stock2Information> res = stockService.queryPagingInform(exchangeCode, lastId, pageSize);
            if (res == null || res.isEmpty()) {
                lastId = null;
                break full;
            }
            logger.info("FullStockFinanceNews.fullStockFinanceNewsExchangeCode stocks:" + res.size());
            lastId = res.get(res.size() - 1).getTickerId();
            procss(res);
        } while (true);

        return lastId;
    }

    private void procss(List<Stock2Information> res) {
        try {
            NewsTaskUtil.multiThreadProcess(res, process, threadPoolTaskExecutor, 3);
            logger.info("FullStockFinanceNewsTask procss end:" + res.size());
        } catch (Exception e) {
            logger.error("FullStockFinanceNewsTask 全量新闻任务失败", e);
        }
    }

    private final Consumer<Stock2Information> process = input -> {
        StockTitle stockTitle = new StockTitle();
        BeanUtils.copyProperties(input, stockTitle);
        stockGoogleNewsHandler.handlerByStockTitle4Google(stockTitle);
		logger.info("News_GoogleFullStock_Task.procss stockTitle:" + stockTitle);
    };
}
